﻿using AFanDa.BLL.BLLService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace AFanDa.Api.Attributes
{
    public class AuthAttribute : Attribute, IAuthorizationFilter
    {

        LoginService _loginService = null;
        public AuthAttribute()
        {
            _loginService = new LoginService();
        }

        public bool AllowMultiple => throw new NotImplementedException();

        public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            // 从请求的请求头获取 token 
            if (actionContext.Request.Headers.TryGetValues("authorization", out IEnumerable<string> tokens))
            {
                //拿到第一个token
                var token = tokens.First();
                try
                {
                    // jwt 解密 token
                    var result = Common.EncryptUtil.UnJWT(token);
                    // 拿出code

                    var controller = actionContext.ControllerContext.Controller as ApiController;

                    if (result == null) { 
                        controller.User = new Models.MyPrincipal()
                        {
                            Identity = new Models.MyIdentity()
                            {
                                Name = "LoginError"
                            }
                        };
                        return await continuation();

                    }

                    var phone = result["phone"].ToString();
                    // 拿出过期时间
                    DateTime time = Convert.ToDateTime(result["time"]);

                    DateTime now = DateTime.Now;
                    // 如果过期返回 401
                    if (now > time)
                    {
                        return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    }
                    // 获取用户信息
                    var iq = _loginService.GetWxUser(phone);
                    // 如果不存在 返回 401 
                    if (!iq.Any())
                    {
                        return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                    }
                    // 验证成功 存入 电话号码
                    controller.User = new Models.MyPrincipal()
                    {
                        Identity = new Models.MyIdentity()
                        {
                            Name = phone
                        }
                    };


                    // 继续后面的代码
                    return await continuation();
                }
                catch (Exception ex)
                {
                    // 如果出现异常返回 401
                    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }
            }
            return new HttpResponseMessage(HttpStatusCode.Unauthorized);


        }
    }
}